//
//  MNDOpenTermsAuthViewController.m
//  minidai
//
//  Created by Vitas on 2018/8/6.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDOpenTermsAuthViewController.h"
#import "MNDAlertViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDWebViewController.h"
#import "UIButton+JKCountDown.h"
#import "UIImage+JKColor.h"

@interface MNDOpenTermsAuthViewController ()<TTTAttributedLabelDelegate>

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *protocolLabel;
@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;

/**
 提示文字
 */
@property (nonatomic, copy) NSString *alertMessage;

@end

@implementation MNDOpenTermsAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.noticeLabel.text = @"应合规要求，出借前需完成出借授权\n(该授权包含缴费授权、债权转让授权以及自动投标授权)";
    self.protocolLabel.delegate = self;
    [self addAgreementLabelAttribute];
    [self loadSignIntroductionMessage];
    [self initialBackButton];
    [self initialRightBarButton];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}

- (void)initialRightBarButton {
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    //    [item setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

#pragma mark - Action

- (void)rightBarButtonAction:(id)sender {
    if (self.alertMessage) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        MNDAlertViewController *alertController = [storyboard instantiateViewControllerWithIdentifier:[MNDAlertViewController description]];
        [KeyWindow addSubview:alertController.view];
        [self.tabBarController addChildViewController:alertController];
        
        alertController.alertTitle = @"温馨提示";
    alertController.alertMessage = self.alertMessage;
    }
}

- (IBAction)goAuthAction:(UIButton *)sender {
    
    kdeclare_weakself;
    NSDictionary *dict = @{
                           @"channel":@"app"
                           };
    
    [APIManager sendRequestWithURL:API_TERMS_AUTH parameters:[MNDSign signedParamWithDict:dict] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"出借授权";
            NSInteger index = 0;
            webVC.fromNaviIndex = index;
            [weakSelf.navigationController pushViewController:webVC animated:YES];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadSignIntroductionMessage {
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_SIGN_INTRODUCTION parameters:[MNDSign signedParamWithDict:@{@"type": @"terms_auth"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.alertMessage = responseModel.data[@"introductions"];
            [weakself initialRightBarButton];
        }
    } onFailure:^(NSError *error) {
        
    }];
}

- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.protocolLabel.highlightedTextColor = kColorDarkOrange;
    //检测类型
    self.protocolLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.protocolLabel.delegate = self;
    //不显示下划线
    self.protocolLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"点击按钮表示您同意《缴费授权协议》《自动投标授权协议》《债权转让授权协议》";
    [self.protocolLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange = [[mutableAttributedString string] rangeOfString:@"《缴费授权协议》" options:NSCaseInsensitiveSearch];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange];
        
        NSRange linkRange1 = [[mutableAttributedString string] rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange1];
        
        NSRange linkRange2 = [[mutableAttributedString string] rangeOfString:@"《债权转让授权协议》" options:NSCaseInsensitiveSearch];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange2];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange = [text rangeOfString:@"《缴费授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url = [NSURL URLWithString:kPaymentAccord];
    [self.protocolLabel addLinkToURL:url withRange:linkRange];
    
    NSRange linkRange1 = [text rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url1 = [NSURL URLWithString:kAutoTenderAccord];
    [self.protocolLabel addLinkToURL:url1 withRange:linkRange1];
    
    NSRange linkRange2 = [text rangeOfString:@"《债权转让授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url2 = [NSURL URLWithString:kAutoTransferAccord];
    [self.protocolLabel addLinkToURL:url2 withRange:linkRange2];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    
    if ([url.absoluteString isEqualToString:kPaymentAccord]) {
        webVC.title = @"缴费授权协议";
    }else if([url.absoluteString isEqualToString:kAutoTenderAccord]){
        webVC.title = @"自动投标授权协议";
    }else{
        webVC.title = @"债权转让授权协议";
    }
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
